<template>
  <el-dialog title="车票信息详情" :visible.sync="isShow" @close="closeDialog" width="50%">
    <!-- 绑定差旅单时显示提示 -->
    <el-alert 
      v-if="isBoundToTravel"
      title="提示：该车票已绑定差旅单，不可修改" 
      type="warning" 
      show-icon 
      style="margin-bottom: 15px;"
    />

    <el-form :model="ticketForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
       <el-input type="hidden" v-model="ticketForm.empno"></el-input> 
       <el-input type="hidden" v-model="ticketForm.travelId"></el-input>

      <el-form-item label="员工姓名" prop="ename">
        <el-input v-model="ticketForm.ename" disabled></el-input>
      </el-form-item>

      <el-form-item label="车票类型" prop="type">
         <el-select 
            v-model="ticketForm.type" 
            placeholder="请选择车票类型" 
            :disabled="isBoundToTravel || typeDisabled"
            style="width: 100%"
          >
            <el-option label="出差" value="出差"></el-option>
            <el-option label="返回" value="返回"></el-option>
          </el-select>
      </el-form-item>

      <!-- 修改后的出发时间选择器 -->
      <el-form-item label="出发时间" prop="startTime">
        <el-date-picker 
          v-model="ticketForm.startTime"
          type="datetime"
          placeholder="请选择出发时间"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 100%;" 
          :disabled="isBoundToTravel"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="出发地点" prop="departure">
        <el-input v-model="ticketForm.departure" placeholder="请输入地点" :disabled="isBoundToTravel || departureDisabled"></el-input>
      </el-form-item>

      <!-- 修改后的到达时间选择器 -->
      <el-form-item label="到达时间" prop="endTime">
        <el-date-picker 
          v-model="ticketForm.endTime"
          type="datetime"
          placeholder="请选择到达时间"
          format="yyyy-MM-dd HH:mm:ss"
          value-format="yyyy-MM-dd HH:mm:ss"
          style="width: 100%;" 
          :disabled="isBoundToTravel"
        ></el-date-picker>
      </el-form-item>

      <el-form-item label="到达地点" prop="arrival">
        <el-input v-model="ticketForm.arrival" placeholder="请输入地点" :disabled="isBoundToTravel || arrivalDisabled" ></el-input>
      </el-form-item>

      <el-form-item label="交通工具" prop="way">
        <el-select v-model="ticketForm.way" placeholder="请选择交通工具" style="width: 100%" :disabled="isBoundToTravel">
          <el-option v-for="trans in transData" :label="trans.name" :value="trans.id" :key="trans.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="车票金额" prop="price">
        <el-input v-model="ticketForm.price" placeholder="请输入金额" :disabled="isBoundToTravel" type="number"></el-input>
      </el-form-item>

      <el-form-item label="车票照片" prop="ticketImage">
        <el-upload
          class="upload"
          action="#"
          list-type="picture-card"
          :show-file-list="false"
          :before-upload="beforeUpload"
          :http-request="handleUpload"
          :on-success="handleSuccess"
          :on-remove="handleRemove"
          :disabled="isBoundToTravel"
        >

          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">确定</el-button>
        <el-button @click="closeDialog">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
export default {
  name: 'ticketInfo',
  props: {
    isShow: Boolean,
    transData: Array,
    ticketInfo: Object
  },
  data() {
    return {
      ticketForm: {
      empno: localStorage.getItem('empno'), 
      ename: localStorage.getItem('ename'), 
      type: '', 
      startTime: '',
      departure: '', 
      endTime: '',
      arrival: '', 
      way: '',
      price: '',
      ticketImage: '',
      isNew: false,
    },
    rules: {
      ename: [{ required: true, message: '请输入员工姓名', trigger: 'blur' }],
      type: [{ required: true, message: '请输入车票类型', trigger: 'blur' }],
      startTime: [{ required: true, message: '请选择出发时间', trigger: 'blur' },
        { validator: this.validateTimeOrder, trigger: ['blur', 'change'] }
      ],
      departure: [{ required: true, message: '请输入出发地点', trigger: 'blur' }],
      endTime: [{ required: true, message: '请选择到达时间', trigger: 'blur' },
        { validator: this.validateTimeOrder, trigger: ['blur', 'change'] }
      ],
      arrival: [{ required: true, message: '请输入到达地点', trigger: 'blur' }],
      way: [{ required: true, message: '请选择交通工具', trigger: 'blur' }],
      price: [{ required: true, message: '请输入车票金额', trigger: 'blur' }]
    },
    latestTicket: null, 
    typeDisabled: false,
    departureDisabled: false,
    arrivalDisabled: false,
    imageUrl: ''
    };
  },
  computed: {
    // 判断是否已绑定差旅单
    isBoundToTravel() {
      return this.ticketForm.travelId != null && this.ticketForm.travelId != 0;
    }
  },
  watch: {
    // 实时监听车票类型变化
  'ticketForm.type'(newVal) {
    this.handleTypeChange(newVal); // 调用处理方法
  },
  isShow(newVal) {
    if (newVal) {
      if (Object.keys(this.ticketInfo).length == 0) {
        this.getLatestTicket(); // 查询最新车票
      }
    }
  },
    ticketInfo: {
    immediate: true,
    deep: true,
    handler(newVal) {
      if (newVal) {
        this.isNew = false;
        this.ticketForm = { ...newVal };
        this.ticketForm.ename = localStorage.getItem('ename');
        this.imageUrl = this.ticketForm.ticketImage; 
        // 编辑时根据类型设置到达地
      if (this.ticketForm.type === '返回') {
        this.ticketForm.arrival = '济南';
        this.arrivalDisabled = true;
      } else {
        this.arrivalDisabled = false;
      }
      } else {
        this.isNew = true;
        this.resetForm();
        this.getLatestTicket(); // 新增时查询最新车票
      }
    }
  }
  },
  methods: {
    submitForm() {
  this.$refs['ruleForm'].validate((valid) => {
    if (valid) {
      const { ticketId, ...ticketData } = this.ticketForm;  // 解构去掉 ticketId
      let url = '/insertTicket';
      if (this.ticketForm.ticketId) {
        url = '/updateTicket';
      }

      this.$http.post(url, this.ticketForm).then(res => {
        if (res.data) {
          this.$emit('ticketSave', res.data);
        } else {
          this.$message.error("保存失败");
        }
      });
    }
  });
},
    resetForm() {
      this.ticketForm = {
        empno: localStorage.getItem('empno'), 
        ename: localStorage.getItem('ename'),
        type: '',
        startTime: '',
        departure: '',
        endTime: '',
        arrival: '',
        way: '',
        price: '',
        ticketImage: '',
        travelId: 0
      };

      if (this.$refs.ruleForm) {
        this.$refs.ruleForm.clearValidate(); // 清除验证状态
      }
      // 重置限制状态
      this.typeDisabled = false;
      this.departureDisabled = false;
      this.arrivalDisabled = false;
      this.imageUrl = '';
      // 新增场景下如果有最新车票，主动处理类型
      if (this.isNew && this.latestTicket) {
        this.setFormRestrictions();
      }
    },

    async closeDialog() {
      // 仅在新增场景且存在上传的图片时，删除图片
      if (this.isNew && this.ticketForm.ticketImage) {
        await this.$http.post('/deleteTicketImage', {
          imageUrl: this.ticketForm.ticketImage
        });
      }
      this.resetForm();
      this.getLatestTicket(); 
      this.$emit('closeDialog');
    },

    // 查询当前员工最新的车票信息
  getLatestTicket() {
    this.$http.get('/getLastTicket?empno=' + localStorage.getItem('empno')).then(res => {
        if (res.data) {
          this.latestTicket = res.data;
          this.setFormRestrictions(); 
          if (this.isNew && this.ticketForm.type) {
            this.handleTypeChange(this.ticketForm.type);
          }
        } else {
          this.latestTicket = null; 
        }
      })
      .catch(() => {
        this.latestTicket = null;
      });
  },
  
  setFormRestrictions() {
    if (!this.latestTicket) return;
    const latestType = this.latestTicket.type;
    this.typeDisabled = false;
    this.departureDisabled = false;
    this.arrivalDisabled = false;
  if (latestType == '返回') {
    this.ticketForm.type = '出差';
    this.typeDisabled = true;
    this.ticketForm.departure = '济南';
    this.departureDisabled = true;
    
    this.handleTypeChange(this.ticketForm.type);
  }
  },
  // 处理车票类型变化
  handleTypeChange(type) {
    if (type === '出差') {
      this.arrivalDisabled = false;
      // 仅当存在最新车票且类型为"返回"时，出发地设为济南
      if (this.latestTicket.type === '返回') {
        this.ticketForm.departure = '济南';
        this.departureDisabled = true;
      } else {
        this.departureDisabled = false;
      }
  } else if (type === '返回') {
    this.ticketForm.arrival = '济南';
    this.arrivalDisabled = true;
    
    this.departureDisabled = false;
    }
  },

  beforeUpload(file) {
    const isJPG = file.type === 'image/jpeg';
    const isPNG = file.type === 'image/png';
    if (!isJPG && !isPNG) {
      this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
      this.$message.error('上传图片大小不能超过 2MB!');
    }
    return isJPG || isPNG && isLt2M;
  },

  async handleUpload(config) {
    const file = config.file;

    if (this.ticketForm.ticketImage) { // 检查是否有旧图片URL
      await this.$http.post('/deleteTicketImage', { 
        imageUrl: this.ticketForm.ticketImage
      });
    }

    const formData = new FormData();
    formData.append('file', file);
    
    this.$http.post('/addPicture', formData).then(res => {
      if (res.data.code === 200) {
        this.ticketForm.ticketImage = res.data.data; 
        config.onSuccess(res.data); 
        this.$message.success('图片上传成功');
      } else {
        config.onError(res.data);
        this.$message.error('图片上传失败：' + res.data.msg);
      }
    });
  },
  
  handleRemove(fileList) {
    if (fileList.length === 0) {
      this.ticketForm.ticketImage = '';
      this.imageUrl = ''; 
    }
  },
    handleSuccess() {
      this.imageUrl = this.ticketForm.ticketImage;
    },
    
    //确保到达时间晚于出发时间
    validateTimeOrder(rule, value,callback) {
    if (!this.ticketForm.startTime || !this.ticketForm.endTime) {
      callback(); 
      return;
    }
    
    // 将时间字符串转换为Date对象
    const startTime = new Date(this.ticketForm.startTime);
    const endTime = new Date(this.ticketForm.endTime);
    
    if (endTime <= startTime) {
      callback(new Error('到达时间必须晚于出发时间'));
    } else {
      callback(); // 验证通过
    }
  },
  }
};
</script>

<style scoped>
.upload-demo i {
  font-size: 28px;
  color: #409EFF;
}

.upload-demo .el-upload {
  width: 100%;
}

.el-form-item {
  margin-bottom: 20px;
}

/* 图片等比例缩放样式 */
.avatar {
  max-width: 100%;
  max-height: 200px;
  width: auto;
  height: auto;
  
  border: 1px solid #eee;
  border-radius: 4px;
}
</style>
